package com.haredot.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.Sign;
import cn.hutool.crypto.asymmetric.SignAlgorithm;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
public class RSA implements EnvironmentAware {

    private Environment environment ;

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment ;
    }

    /**
     * 数字签名
     * 返回的签名如果需要进行网络传输，可能需要进行URLEncode 编码
     * @param rawText
     * @return
     */
    public  String sign(String rawText) {
        String publicKey = this.environment.getProperty("sys.email.rsa-public-key") ;
        String privateKey = this.environment.getProperty("sys.email.rsa-private-key") ;
        // 进行数字签名的对象
        Sign sign = SecureUtil.sign(SignAlgorithm.SHA256withRSA, privateKey, publicKey);
        // 获取签名后的结果
        byte[] sign1 = sign.sign(rawText.getBytes(StandardCharsets.UTF_8));
        // 对签名后的结果 进行 Base64编码
        String encode = Base64.encode(sign1);
        return encode ;
    }

    /**
     * 数字认证
     * @param rawText
     * @param sign
     * @return
     */
    public  boolean verify(String rawText, String sign) {
        String publicKey = this.environment.getProperty("sys.email.rsa-public-key") ;
        String privateKey = this.environment.getProperty("sys.email.rsa-private-key") ;
        // 进行数字签名的对象
        Sign secureSign = SecureUtil.sign(SignAlgorithm.SHA256withRSA, privateKey, publicKey);
        // 使用 URLDecode 进行解码
        // 进行 Base64解码
        byte[] decode1 = Base64.decode(sign);
        // 对内容进行认证，查看是否被篡改
        return secureSign.verify(rawText.getBytes(StandardCharsets.UTF_8), decode1);
    }

}
